/**
 * GroupController.java
 * Version 1.0.0
 * Created on 2019年1月16日
 */
package com.yincheng.oes.business.group.controller;

import com.yincheng.oes.business.group.model.entity.GroupInfo;
import com.yincheng.oes.business.group.model.query.ExportGroupUsersReq;
import com.yincheng.oes.business.group.service.GroupService;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.io.FilenameUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

/**
 * @author yangsy
 * @version 1.0.0
 * @since 创建时间：2019年1月16日
 * <p>
 * 功能描述：
 * <p>
 * 邮箱地址：446948434@qq.com
 */
@Controller
@RequestMapping("/group")
public class GroupController {
    private static final Logger logger = LogManager.getLogger(GroupController.class);
    @Autowired
    private GroupService groupService;

    /**
     * 创建班级组信息
     *
     * @param view
     * @return
     */
    @RequestMapping(value = "/createGroup", method = RequestMethod.GET)
    public ModelAndView draftPaper(ModelAndView view) {
        setView(view);
        String id = UUID.randomUUID().toString();
        view.addObject("groupId", id);
        view.setViewName("redirect:/group/editGroupPage.html");
        return view;
    }

    /**
     * 获取班级组信息以及班级组内人员列表信息
     *
     * @param view
     * @param groupId
     * @return
     */
    @RequestMapping(value = "/editGroupPage.html", method = RequestMethod.GET)
    public ModelAndView editPaperPage(ModelAndView view, String groupId) {
        setView(view);
        GroupInfo groupInfo = groupService.getGroupInfo(groupId);
        view.addObject("form", groupInfo);
        view.setViewName("/business/group/group-edit");
        return view;
    }

    @RequestMapping(value = "/readGroupPage.html", method = RequestMethod.GET)
    public ModelAndView readGroupPage(ModelAndView view, String groupId) {
        setView(view);
        GroupInfo groupInfo = groupService.getGroupInfo(groupId);
        view.addObject("form", groupInfo);
        view.setViewName("/business/group/group-read");
        return view;
    }

    /**
     * 保存班级组及班级组内用户信息
     *
     * @param groupInfo
     */
    @RequestMapping(value = "/saveGroupInfo.json", method = RequestMethod.POST)
    public void savePaper(GroupInfo groupInfo) {
        groupService.saveGroup(groupInfo);
    }

    private void setView(ModelAndView view) {

    }

    @InitBinder // 类初始化是调用的方法注解
    public void initBinder(WebDataBinder binder) {
        // 给这个controller配置接收list的长度1024，仅在这个controller有效
        binder.setAutoGrowCollectionLimit(1024);
    }

    @RequestMapping(value = "/excel/exportGroupUsers.json", method = RequestMethod.GET)
    public void exportGroupUsers(ExportGroupUsersReq req, HttpServletResponse response)
            throws Exception {
        long start = System.currentTimeMillis();
        GroupInfo groupInfo = groupService.getGroupInfo(req.getGroupId());
        String fileName = groupInfo.getGroup().getGroupName() + ".xlsx";
        String newName = URLEncoder.encode(fileName, "UTF-8");
        response.reset();
        response.setContentType(getContextType(fileName));
        response.setHeader("Content-disposition", "attachment; filename=" + newName);
        groupService.exportGroupUsers(response.getOutputStream(), req);
        logger.debug("exportGroupUsers cost {} ms", System.currentTimeMillis() - start);

    }


    private static String getContextType(String filename) {
        String extension = FilenameUtils.getExtension(filename).toLowerCase();
        String context = contextMap.get(extension);

        if (context != null) {
            return context + "; charset=utf-8";
        } else {
            return "application/octet-stream; charset=utf-8";
        }
    }

    private static final Map<String, String> contextMap = new HashMap<>();

    static {
        contextMap.put("xls", "application/-excel");
        contextMap.put("xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        contextMap.put("doc", "application/vnd.msword");
        contextMap.put("docx", "application/octet-stream");
        contextMap.put("ppt", "applications/-powerpoint");
    }

}
